
var fs = require('fs');
var Evt = require('events').EventEmitter;
var util = require('util');
var crypto = require('crypto');

var   root="D:\\nginx-1.11.7\\nginx-1.11.7\\html\\newsyhall\\h5_taihanghall";
var   root=__dirname;

// await 关键字后的函数
var Delay_Time = function(ms) {
    return new Promise(function(resolve) {
        setTimeout(resolve, 1000)
    } )
}
// async 函数
var Delay_Print = async function(ms) {
    await Delay_Time(ms)
    return new Promise(function(resolve, reject) {
        resolve("End");
    })
}
// 执行async函数后
Delay_Print(1000).then(function(resolve) {
    console.log(resolve);
})


var  list=[];
var   content="";
function readDirSync(path){

    var pa = fs.readdirSync(path);
    pa.forEach(function(ele,index){
        var info = fs.statSync(path+"/"+ele)
        if(info.isDirectory()){
            console.log("dir: "+ele)
            if(ele=='.git'||ele==".idea")
            {
                return;
            }
            readDirSync(path+"/"+ele);
        }else{

            var  relatePath=path.replace(root,'')

            var   url=relatePath+"/"+ele;
            var   fulePath="";
            if(ele.indexOf('js')>0)
            {
                fullPath=path+"/"+ele
                var str=fs.readFileSync(fullPath);
                content+=str;
            }
            //fullPath=path+"/"+ele
            console.log("url="+url)
            url=url.replace(/\\/g,'/');
            var  obj={url:url,md5:''};
            list.push(obj)
        }
    })


}


readDirSync(root+'/res')

var    fileList=list;

var  readFileMd5=async function(fileName)
{
    var    Ticker=function(){};
    util.inherits(Ticker,Evt);
    var ticker = new Ticker();
    var loaded = new Promise(function(resolve, reject) {ticker.on("tick", resolve);});
    var  retMd5="";
    //从文件创建一个可读流
    var stream = fs.createReadStream(fileName);
    var fsHash = crypto.createHash('md5');
    stream.on('data', function(d) {
        fsHash.update(d);
    });
    stream.on('end', function() {
        var md5 = fsHash.digest('hex');
        console.log("文件的MD5是：%s", md5);
        retMd5=md5;
        ticker.emit('tick',md5);
    });
    await loaded.then(function(path){ });
    return retMd5;
}



var  calAllFile=async function()
{
    var  sfile=root;
    var   t1=new Date().getTime()
    var  map={};
    for(var i in fileList)
    {
        var  it=fileList[i]
        var  path=sfile+it.url;
        it.v=await readFileMd5(path)
        var  url=it.url.replace('/','')
        map[url]=it.v;
    }
    var  t=new Date().getTime()-t1;
    var  str="var  fileVersion="+JSON.stringify(map)
    fs.writeFileSync("version.js",str)
    console.log("time ",t,str);
}


calAllFile();